﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using NetBay.Core.BusinessEntities;
using NetBay.Core.BusinessEntities.Barcodes;
using NetBay.Core.BusinessEntities.Historic;
using NetBay.Core.Silverlight.Tools;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.Enums;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.CriteriaControls;
using Rio.Framework.Pages.Helpers.Utils;
using Rio.Framework.Pages.Manager;
using Rio.Framework.Pages.Viewer;
using Rio.Framework.WCFService;
using RIOWCFSERVICE = Rio.Framework.WCFService.RioWcfServices;
using ImageRio = Rio.Framework.WCFService.RioWcfServices.ImageRio;
using GalaSoft.MvvmLight.Command;
using Rio.Framework.Pages.ChildWindows;
using Rio.Framework.Pages.AppCode.Models;

namespace Rio.Framework.Pages.Controls
{
    public partial class IndexPanel
    {
        #region Attributs

        private bool _useChronoGeneration;
        private BarcodeManager _barcodeManager;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets a value indicating whether [use chrono generation].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [use chrono generation]; otherwise, <c>false</c>.
        /// </value>
        public bool UseChronoGeneration
        {
            get
            {
                return _useChronoGeneration;
            }
            set
            {
                _useChronoGeneration = value;
                OnPropertyChanged("UseChronoGeneration");
            }
        }

        /// <summary>
        ///Use in AddDocumentChildWindow for workflow
        // Keep Folder and Organization to build the link to the answer folder in comment
        /// </summary>
        /// <value>The folder id after indexation.</value>
        public long FolderIdAfterIndexation { get; set; }

        /// <summary>
        /// Gets or sets the folder id doc after indexation.
        /// </summary>
        /// <value>The folder id doc after indexation.</value>
        public string FolderIdDocAfterIndexation { get; set; }

        /// <summary>
        /// Gets or sets the minimize control toolbar command.
        /// </summary>
        /// <value>The minimize control toolbar command.</value>
        public RelayCommand<bool> MinimizeControlToolbarCommand { get; set; }

        /// <summary>
        /// Gets or sets the search command.
        /// </summary>
        /// <value>
        /// The search command.
        /// </value>
        public RelayCommand SearchCommand { get; set; }

        /// <summary>
        /// Gets or sets the clear criteria command.
        /// </summary>
        /// <value>
        /// The clear criteria command.
        /// </value>
        public RelayCommand ClearCriteriaCommand { get; set; }

        /// <summary>
        /// Gets or sets the import command.
        /// </summary>
        /// <value>
        /// The import command.
        /// </value>
        public RelayCommand ImportCommand { get; set; }

        /// <summary>
        /// Gets or sets the index command.
        /// </summary>
        /// <value>
        /// The index command.
        /// </value>
        public RelayCommand IndexCommand { get; set; }

        /// <summary>
        /// Gets or sets the scan command.
        /// </summary>
        /// <value>
        /// The scan command.
        /// </value>
        public RelayCommand ScanCommand { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="IndexPanel" /> class.
        /// </summary>
        public IndexPanel()
            : base()
        {
            InitializeComponent();

            MinimizeControlToolbarCommand = new RelayCommand<bool>(MinimizeControlToolbar);

            documentInformationsPanelControl.IsEnabled = false;

            //Desactivate indexation until citeria list are not loaded
            //checkBoxProcessLAD.IsEnabled = false;
            //checkBoxProcessCAB.IsEnabled = false;
            checkBoxProcessLAD.Visibility = Boolean.Parse(GlobalWebContext.RioAppSettings["AllowOcrFunctionnality"]) ? Visibility.Visible : System.Windows.Visibility.Collapsed;
            checkBoxProcessCAB.Visibility = Boolean.Parse(GlobalWebContext.RioAppSettings["AllowCABFunctionnality"]) ? Visibility.Visible : System.Windows.Visibility.Collapsed;

            InitLabel();
            InitCriteriaCheckbox();

            Unloaded += new RoutedEventHandler(IndexPanel_Unloaded);
            LayoutRoot.KeyDown += LayoutRoot_KeyDown;
            uCOrganizationType.OrganizationSelected += cbEntity_SelectionChanged;
            uCOrganizationType.FolderSelected += cbFolderType_SelectionChanged;

            //BarcodeManager
            _barcodeManager = new BarcodeManager();
            _barcodeManager.BarcodeProcessed += barcodeManager_BarcodeProcessed;
            _barcodeManager.IndexingFinished += barcodeManager_IndexingFinished;
            _barcodeManager.BeforeIndexing += barcodeManager_BeforeIndexing;
            _barcodeManager.IndexingError += barcodeManager_IndexingError;
            _barcodeManager.NeedIndexCriteria += barcodeManager_NeedIndexCriteria;
            _barcodeManager.IndexingAborted += barcodeManager_IndexingAborted;

            //Init Mvvm Command
            InitCommand();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="IndexPanel" /> class.
        /// </summary>
        /// <param name="P_oListVignetteFromImportPage">The list vignette from import page.</param>
        /// <param name="P_oViewerControlFromImportPage">The viewer control from import page.</param>
        /// <param name="P_oListViewer">The list viewer.</param>
        public IndexPanel(ThumbnailPanel P_oListVignetteFromImportPage, UCViewer P_oViewerControlFromImportPage, ListViewer P_oListViewer)
            : this()
        {
            CurrentIndexMode = AppDisplayMode.Import;
            InitOrganizationAndFolderType(CurrentIndexMode);

            m_oListViewer = P_oListViewer;
            m_oListViewer.UserId = GlobalWebContext.CurrentUser.UserId;

            m_oListVignetteFromImportPage = P_oListVignetteFromImportPage;
            m_oListVignetteFromImportPage.RefreshViewerAfterIndex += m_oListVignetteFromImportPage_RefreshThumbnails;
            m_oViewerControlFromImportPage = P_oViewerControlFromImportPage;
            m_oListVignetteFromImportPage.UserId = GlobalWebContext.CurrentUser.UserId;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="IndexPanel" /> class.
        /// </summary>
        /// <param name="P_oListVignetteFromImportPage">The list vignette from import page.</param>
        /// <param name="P_oViewerControlFromImportPage">The viewer control from import page.</param>
        /// <param name="P_oListViewer">The list viewer.</param>
        /// <param name="P_oOrganization">The organization.</param>
        /// <param name="P_oFolderType">Type of the folder.</param>
        /// <param name="p_oCurrentFolder">The current folder.</param>
        /// <param name="appDisplayMode">The app display mode.</param>
        public IndexPanel(ThumbnailPanel P_oListVignetteFromImportPage, UCViewer P_oViewerControlFromImportPage, ListViewer P_oListViewer, Organization P_oOrganization, FolderType P_oFolderType, Folder p_oCurrentFolder, AppDisplayMode appDisplayMode = AppDisplayMode.AddDocument)
            : this()
        {
            CurrentIndexMode = appDisplayMode;
            InitOrganizationAndFolderType(CurrentIndexMode);

            m_oListViewer = P_oListViewer;
            m_oListViewer.UserId = GlobalWebContext.CurrentUser.UserId;
            m_oListVignetteFromImportPage = P_oListVignetteFromImportPage;
            m_oViewerControlFromImportPage = P_oViewerControlFromImportPage;
            m_oListVignetteFromImportPage.UserId = GlobalWebContext.CurrentUser.UserId;
            ;

            m_oOrganization = P_oOrganization;
            m_oFolderType = P_oFolderType;
            CurrentFolder = p_oCurrentFolder;

            uCOrganizationType.SelectedOrganization = m_oOrganization;
            uCOrganizationType.SelectedFolderType = m_oFolderType;
        }

        #endregion

        #region Public Functions

        /// <summary>
        /// Translation
        /// </summary>
        public override sealed void InitLabel()
        {
            base.InitLabel();
            indexBarItem.Header = Resx.GetLabel(ResxIndexPanel.INDEX_TAB_HEADER);
            itemsPanelControl.Header = Resx.GetLabel(ResxIndexPanel.ITEMS);
            documentInformationsPanelControl.Header = Resx.GetLabel(ResxIndexPanel.INFO_DOCUMENT);
            labelNote.Text = Resx.GetLabel(ResxIndexPanel.NOTE);
            labelAuthor.Text = Resx.GetLabel(ResxIndexPanel.AUTHOR);
            checkBoxFullText.Content = Resx.GetLabel(ResxIndexPanel.FULLTEXT_ENABLE);
            checkBoxKeepCriteria.Content = Resx.GetLabel(ResxIndexPanel.KEEP_CRITERIA_CHECKBOX);
            TextBlockClear.Text = Resx.GetLabel(ResxIndexPanel.CLEAR_CRITERIA);
            TextBlockToIndex.Text = Resx.GetLabel(ResxIndexPanel.TOINDEX);
            checkBoxProcessLAD.Content = Resx.GetLabel(ResxIndexPanel.RUNOCR);
            TextBlockToSearch.Text = Resx.GetLabel(ResxIndexPanel.SEARCH);
            checkBoxProcessCAB.Content = Resx.GetLabel(ResxIndexPanel.RUNCAB);
        }

        /// <summary>
        /// Disables the panel for search mode.
        /// </summary>
        public void DisablePanelForSearchMode()
        {
            uCOrganizationType.SetIsEnabledComboBoxProperty(false);
            indexContentControl.IsEnabled = false;
            buttonClear.IsEnabled = false;
            buttonToSearch.IsEnabled = false;
        }

        /// <summary>
        /// Performs the import by a request in URI.
        /// </summary>
        public void PerformImportByUri()
        {
            //Find Organization
            Organization organization = uCOrganizationType.Organizations.Where(o => o.Identifier == QueryByUriManager.ImportInstance.OrganizationId).FirstOrDefault();

            //Listen the change of ItemsSource of FolderType ListBox
            uCOrganizationType.FolderTypeSourceChanged += UcOrganizationTypeFolderTypeSourceChanged;

            //Set Organization
            uCOrganizationType.SelectedOrganization = organization;
        }

        private void UcOrganizationTypeFolderTypeSourceChanged(object sender, EventArgs e)
        {
            uCOrganizationType.FolderTypeSourceChanged -= UcOrganizationTypeFolderTypeSourceChanged;

            FolderType folderType = uCOrganizationType.FolderTypes.Where(f => f.Identifier == QueryByUriManager.ImportInstance.FolderTypeId).FirstOrDefault();

            //Attach to this event to be sure that all indexes are loaded to fill its with query string
            stackIndex.IndexLoaded += IndexPanelIndexLoaded;

            //Set FolderType
            uCOrganizationType.SelectedFolderType = folderType;
        }

        private void IndexPanelIndexLoaded(object sender, EventArgs e)
        {
            stackIndex.IndexLoaded -= IndexPanelIndexLoaded;

            //Set Index value for each control
            foreach (KeyValuePair<int, string> item in QueryByUriManager.ImportInstance.IndexArgs)
                stackIndex[item.Key - 1] = item.Value;

            QueryByUriManager.Finish();
        }

        /// <summary>
        /// Switches the enablity search button.
        /// </summary>
        /// <param name="isEnabled">if set to <c>true</c> [is enabled].</param>
        public void SwitchEnablitySearchButton(bool isEnabled)
        {
            buttonToSearch.IsEnabled = isEnabled;
            uCOrganizationType.IsEnabled = isEnabled;
        }

        #endregion

        #region Protected Functions

        /// <summary>
        /// Index selected files in viewer
        /// </summary>
        public override void IndexFiles()
        {
            m_oListVignetteFromImportPage.SetActuallyRankingList();

            m_iCounterIndexedDocOk = 0;
            m_iCounterErrorOnIndex = 0;
            m_iNumberOfDocumentToAdd = 0;

            if (m_oListSelectedFilename != null)
            {
                DesactivatePanel();
                m_iActivePanel = 1;
            }
            else
            {
                m_iActivePanel = 0;
            }

            string L_oSelectedNodeCode = "000000000000";
            if ((m_oOrganization != null) && (m_oFolderType != null))
            {
                OnBeforeIndexing();

                //List of criteria and values
                Dictionary<long, string> l_oCriteriaFilter;
                Dictionary<long, string> l_oUnicityIndex;

                //If all mandatory criteria are inputed, we can follow the indexation
                if (stackIndex.IsMandatoryIndexSatisfied())
                {
                    l_oCriteriaFilter = stackIndex.GetIndexIdValues();
                    l_oUnicityIndex = stackIndex.GetUniqueIndexValues();

                    //Selected item code
                    if (treeViewControlItems.CurrentSelectedItem != null)
                    {
                        L_oSelectedNodeCode = treeViewControlItems.CurrentSelectedItem.Code;
                    }

                    //** check if folder exist with specified index
                    GetDataContext.IsFolderExist(m_oOrganization.Identifier, m_oFolderType.Identifier, l_oCriteriaFilter, false, delegate(InvokeOperation<ReturnLong> retr)
                    {
                        if (retr != null && retr.Value != null && retr.Value.Value != 0)
                        {
                            if ((m_oListSelectedFilename != null) && (m_oListSelectedFilename.Count > 0))
                            {
                                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szMsgFolderExists, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                                L_oMessage.ShowDialog();
                                L_oMessage.Closed += (s, ev) =>
                                {
                                    if (L_oMessage.Result == MessageBoxResult.Yes)
                                    {
                                        SplashScreenManager.Wait(this);
                                        RunIndexing(m_oListSelectedFilename, l_oCriteriaFilter, L_oSelectedNodeCode);
                                    }
                                    else
                                    {
                                        SplashScreenManager.Stop(this);
                                        ActivatePanel();
                                    }
                                };
                            }
                            else
                            {
                                MessageBoxChildWindow noDocSelectedWindow = new MessageBoxChildWindow("",
                                                                                                      Resx.GetLabel(ResxIndexPanel.MSG_NOT_DOC_SELECTED),
                                                                                                      MessageBoxButtons.Ok,
                                                                                                      MessageBoxIcon.Warning);
                                noDocSelectedWindow.ShowDialog();
                                noDocSelectedWindow.Closed += (s1, ev1) =>
                                                                  {
                                                                      SplashScreenManager.Stop(this);
                                                                      ActivatePanel();
                                                                  };
                            }
                        }
                        else
                        {
                            //** if no folder found check unicity of the index
                            GetDataContext.CheckUnicityOfIndexValue(m_oFolderType.Identifier, l_oUnicityIndex, 0, delegate(InvokeOperation<IEnumerable<long>> CheckUnicityReturn)
                            {
                                if (CheckUnicityReturn.Value != null && !CheckUnicityReturn.Value.Any())
                                {
                                    SplashScreenManager.Wait(this);
                                    if ((m_oListSelectedFilename != null) && (m_oListSelectedFilename.Count > 0))
                                    {
                                        RunIndexing(m_oListSelectedFilename, l_oCriteriaFilter, L_oSelectedNodeCode);
                                    }
                                    else
                                    {
                                        SplashScreenManager.Stop(this);
                                        MessageBoxChildWindow L_oEmptyDirectoryMsg = new MessageBoxChildWindow("", Resx.GetLabel(ResxIndexPanel.MSG_FOLDER_EMPTY).Replace("\\n", Environment.NewLine), MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                                        L_oEmptyDirectoryMsg.ShowDialog();
                                        L_oEmptyDirectoryMsg.Closed += (s1, ev1) =>
                                        {
                                            if (L_oEmptyDirectoryMsg.Result == MessageBoxResult.Yes)
                                            {
                                                SplashScreenManager.Wait(this);
                                                InvokeAddDocumentQuery(l_oCriteriaFilter, null, L_oSelectedNodeCode, null);
                                            }
                                            else
                                            {
                                                SplashScreenManager.Stop(this);
                                                ActivatePanel();
                                            }
                                        };
                                    }
                                }
                                else
                                {
                                    //highlight control
                                    List<long> l_oListIndex = new List<long>(CheckUnicityReturn.Value);
                                    stackIndex.ChangeBorderColor(l_oListIndex, Colors.Red);
                                    SplashScreenManager.Stop(this);
                                    ActivatePanel();
                                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szMsgNoUnicity, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                                    L_oMessage.ShowDialog();
                                }
                            }, null); //CheckUnicityOfIndexValue
                        }
                    }, null);//IsFolderExist
                }
                else
                {
                    //
                    SplashScreenManager.Stop(this);
                    ActivatePanel();
                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szLabelMandatoryField, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                    L_oMessage.ShowDialog();
                }
            }
            else
            {
                SplashScreenManager.Stop(this);
                ActivatePanel();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected void ClearCriterias()
        {
            stackIndex.ClearCriterias();
            ClearDocumentInformation();
            checkBoxFullText.IsChecked = true;

            //uCOrganizationType.ClearSelectedOrganization();
            //uCOrganizationType.ClearSelectedFolder();
        }

        /// <summary>
        /// Clear the selected item       
        /// </summary>
        protected void ClearSelectedItem()
        {
            treeViewControlItems.ClearSelection();
        }

        /// <summary>
        /// 
        /// </summary>
        protected void ClearDocumentInformation()
        {
            textboxAuthor.Text = String.Empty;
            textboxNote.Text = String.Empty;
            checkBoxFullText.IsChecked = false;
        }

        #endregion

        #region Private Functions

        /// <summary>
        /// Inits the command.
        /// </summary>
        private void InitCommand()
        {
            SearchCommand = new RelayCommand(OnSearchActionPerformed);
            ClearCriteriaCommand = new RelayCommand(OnClearCriteriaActionPerformed);
            ImportCommand = new RelayCommand(OnImportActionPerformed);
            ScanCommand = new RelayCommand(OnScanActionPerformed);
            IndexCommand = new RelayCommand(OnIndexActionPerformed);
        }

        /// <summary>
        /// Called when [scan action performed].
        /// </summary>
        private void OnScanActionPerformed()
        {
        }

        /// <summary>
        /// Called when [import action performed].
        /// </summary>
        private void OnImportActionPerformed()
        {
        }

        /// <summary>
        /// Called when [index action performed].
        /// </summary>
        private void OnIndexActionPerformed()
        {
            if (checkBoxProcessCAB.IsChecked != null && checkBoxProcessCAB.IsChecked.Value)
            {
                DoBarcodeProcess();
            }
            else if (checkBoxProcessLAD.IsChecked != null && checkBoxProcessLAD.IsChecked.Value)
            {
                DoOCRProcess();
            }
            else
            {
                IndexFiles();
            }

        }

        /// <summary>
        /// Called when [search action performed].
        /// </summary>
        private void OnSearchActionPerformed()
        {
            //Get the list of values for each index
            Dictionary<long, string> listIndexValue = stackIndex.GetIndexIdValuesToSearch();

            SearchFinished += IndexPanel_SearchFinished;

            try
            {
                Search(m_oOrganization, m_oFolderType, listIndexValue);
            }
            catch
            {
                SearchFinished -= IndexPanel_SearchFinished;

                MessageBoxChildWindow L_oCriteriaMessage = new MessageBoxChildWindow(String.Empty, m_sLblNoCriteria, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oCriteriaMessage.ShowDialog();
            }
        }

        /// <summary>
        /// Called when [clear criteria action performed].
        /// </summary>
        private void OnClearCriteriaActionPerformed()
        {
            ClearCriterias();
        }

        /// <summary>
        /// Inits the type of the organization and folder.
        /// </summary>
        /// <param name="p_oAppDisplayMode">The p_o app display mode.</param>
        private void InitOrganizationAndFolderType(AppDisplayMode p_oAppDisplayMode)
        {
            //UCOrganizationType init
            uCOrganizationType.OrganizationSelected += cbEntity_SelectionChanged;
            uCOrganizationType.FolderSelected += cbFolderType_SelectionChanged;
            uCOrganizationType.InitControl(p_oAppDisplayMode);
        }

        /// <summary>
        /// Handles the Unloaded event of the IndexPanel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void IndexPanel_Unloaded(object sender, RoutedEventArgs e)
        {
            if (_barcodeManager != null)
            {
                _barcodeManager.BarcodeProcessed -= barcodeManager_BarcodeProcessed;
                _barcodeManager.IndexingFinished -= barcodeManager_IndexingFinished;
                _barcodeManager.BeforeIndexing -= barcodeManager_BeforeIndexing;
                _barcodeManager.IndexingError -= barcodeManager_IndexingError;
                _barcodeManager.NeedIndexCriteria -= barcodeManager_NeedIndexCriteria;
                _barcodeManager.IndexingAborted -= barcodeManager_IndexingAborted;
            }
        }

        /// <summary>
        /// Runs the indexing.
        /// </summary>
        /// <param name="imagesToIndex">Index of the images to.</param>
        /// <param name="indexCriteria">The index criteria.</param>
        /// <param name="selectedItemCode">The selected item code.</param>
        private void RunIndexing(List<ImageRio> imagesToIndex, Dictionary<long, string> indexCriteria, string selectedItemCode)
        {
            Object l_oImageToDisplayAfterIndexing = null;
            List<string> l_oListTemp = new List<string>();
            m_iNumberOfDocumentToAdd = 0;
            m_DirectoryListToImport = new List<ImageRio>();

            if (imagesToIndex != null && imagesToIndex.Count > 0)
            {
                for (int numberOfAddedDoc = 0; numberOfAddedDoc < imagesToIndex.Count; numberOfAddedDoc++)
                {
                    if (imagesToIndex.ElementAt(numberOfAddedDoc).isDirectory)
                    {
                        //add a directory content, each files inside the directory
                        m_DirectoryListToImport.Add(imagesToIndex.ElementAt(numberOfAddedDoc));
                        IList<ImageRio> l_oListTempSubFile = imagesToIndex.ElementAt(numberOfAddedDoc).FileList;
                        l_oListTemp.AddRange(l_oListTempSubFile.Select((t, m_iNumberOfSubAddedDoc) => Utils.RemoveExtension(l_oListTempSubFile.ElementAt(m_iNumberOfSubAddedDoc).Name)));
                    }
                    else
                    {
                        //add a single image
                        l_oListTemp.Add(Utils.RemoveExtension(imagesToIndex.ElementAt(numberOfAddedDoc).Name));
                    }
                }
            }

            //Execute query    
            m_iNumberOfDocumentToAdd = l_oListTemp.Count; //number of document to add
            l_oImageToDisplayAfterIndexing = m_oListSelectedFilename.ElementAt(m_oListSelectedFilename.Count - 1);
            InvokeAddDocumentQuery(indexCriteria, l_oListTemp, selectedItemCode, l_oImageToDisplayAfterIndexing);
        }

        /// <summary>
        /// Invokes the add document query.
        /// </summary>
        /// <param name="p_oCriteriaFilter">The criteria filter.</param>
        /// <param name="p_oListTemp">The list temp.</param>
        /// <param name="p_oSelectedNodeCode">The selected node code.</param>
        /// <param name="p_oImageToDisplayAfterIndexing">The image to display after indexing.</param>
        private void InvokeAddDocumentQuery(Dictionary<long, string> p_oCriteriaFilter, List<string> p_oListTemp, string p_oSelectedNodeCode, object p_oImageToDisplayAfterIndexing)
        {
            var query = GetDataContext.AddDocumentQuery(m_oOrganization.Identifier, m_oFolderType.Identifier,
                p_oCriteriaFilter,
                p_oListTemp,
                p_oSelectedNodeCode,
                textboxNote.Text.Trim(), textboxAuthor.Text.Trim(),
                "", ChronoName, ChronoId, true);

            GetDataContext.Load(query, OnAddDocumentQueryCallback, p_oImageToDisplayAfterIndexing);
        }

        /// <summary>
        /// Launch the search
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonToIndex_Click(object sender, RoutedEventArgs e)
        {

        }

        /// <summary>
        /// The selected organization change
        /// We have to reload the corresponding folder type
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbEntity_SelectionChanged(object sender, OrganizationSelectedEventArgs e)
        {
            m_oOrganization = e.Organization;

            documentInformationsPanelControl.IsEnabled = false;
            treeViewControlItems.ClearItems();

            buttonClear.IsEnabled = false;
            buttonToSearch.IsEnabled = false;
        }

        /// <summary>
        /// The selected organization change
        /// We have to load indexes controls
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// </summary>
        private void cbFolderType_SelectionChanged(object sender, FolderSelectedEventArgs e)
        {
            //Desactivate indexation until citeria list are not loaded
            buttonToIndex.IsEnabled = checkBoxProcessCAB.IsChecked.Value;
            treeViewControlItems.ClearItems();
            m_oFolderType = e.FolderType;

            //Clear folder if selected folder change
            if (CurrentIndexMode != AppDisplayMode.AddDocument)
            {
                CurrentFolder = null;
            }

            if (this.CurrentFolder == null)
            {
                buttonClear.IsEnabled = e.FolderType != null;
                buttonToSearch.IsEnabled = e.FolderType != null;
            }

            InitPanelControls();
        }

        /// <summary>
        /// Inits the panel controls.
        /// </summary>
        private void InitPanelControls()
        {
            if (m_oFolderType != null)
            {
                if (CurrentFolder == null)
                {
                    uCOrganizationType.SetIsEnabledComboBoxProperty(false);
                }

                //Initialize index control panel
                InitIndexControl();

                //Initialize item panel
                InitItems(m_oFolderType);

                ClearDocumentInformation();
                checkBoxFullText.IsChecked = true;

                documentInformationsPanelControl.IsEnabled = true;
            }
        }

        /// <summary>
        /// run indexing with enter key
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LayoutRoot_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && buttonToIndex.IsEnabled)
            {
                buttonToIndex_Click(this, null);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_oListVignetteFromImportPage_RefreshThumbnails(object sender, EventArgs e)
        {
            m_oViewerControlFromImportPage.LoadImageFromDocument(GlobalWebContext.CurrentUser.UserId, m_oListVignetteFromImportPage.ListAllDocFileName, 0, false);
        }

        /// <summary>
        /// Add index criteria control with help assistance values (with filter)
        /// </summary>
        private void InitIndexControl()
        {
            if ((m_oOrganization != null) && (m_oFolderType != null))
            {
                if ((CurrentFolder != null) && (CurrentFolder.ListValues != null))
                {
                    InitExistingFolder();
                }
                else
                {
                    InitNonExistingFolder();
                }
            }
        }

        /// <summary>
        /// Create control with no data
        /// </summary>
        private void InitNonExistingFolder()
        {
            OnIndexLoaded();
            uCOrganizationType.SetIsEnabledComboBoxProperty(true);

            //Activate indexation
            buttonToIndex.IsEnabled = true;

            //Activate BarCode Traitment.
            checkBoxProcessCAB.IsEnabled = true;
        }

        /// <summary>
        /// Create control with data for an existing folder
        /// </summary>
        private void InitExistingFolder()
        {
            //Activate indexation
            buttonToIndex.IsEnabled = true;
            checkBoxProcessCAB.IsEnabled = true;

            OnIndexLoaded();
        }

        /// <summary>
        /// Handles the GotFocus event of the L_oUiElementIndexControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void L_oUiElementIndexControl_GotFocus(object sender, RoutedEventArgs e)
        {
            if (sender is FrameworkElement)
            {
                indexScrollViewer.ScrollIntoView(sender as FrameworkElement);
            }
        }

        /// <summary>
        /// Initialize items'treeview from a XDocument
        /// </summary>
        /// <param name="P_oFolderType">Type of the folder.</param>
        private void InitItems(FolderType P_oFolderType)
        {
            treeViewControlItems.InitItems(P_oFolderType);
            treeViewControlItems.SelectDefaultItem();
            if (treeViewControlItems.ItemsList.Count == 1)
            {
                itemsPanelControl.IsEnabled = false;
            }
            else
            {
                itemsPanelControl.IsEnabled = true;
            }
        }

        /// <summary>
        /// Occurs when a document was added to RIO
        /// Call MoveImportDocument Wcf
        /// </summary>
        /// <param name="result">The result.</param>
        private void OnAddDocumentQueryCallback(LoadOperation<Document> result)
        {
            try
            {
                List<Document> l_oReturnObjects = new List<Document>(result.Entities);

                if (l_oReturnObjects.Count > 0)
                {
                    Document l_oFirst = l_oReturnObjects.First();

                    if (l_oFirst.IsValid)
                    {
                        FolderIdAfterIndexation = l_oFirst.FolderId;
                        FolderIdDocAfterIndexation = l_oFirst.FolderIdentifier;

                        ObservableCollection<WCFService.RioWcfServices.Document> l_oObservableCollection = new ObservableCollection<WCFService.RioWcfServices.Document>();

                        //Add document to ventilate
                        foreach (Document l_oDoc in l_oReturnObjects)
                        {
                            WCFService.RioWcfServices.Document l_oWCFDoc = new WCFService.RioWcfServices.Document
                            {
                                Identifier = l_oDoc.Identifier,
                                ImageName = l_oDoc.ImageName,
                                RelativePath = l_oDoc.RelativePath,
                                MultiVolumePath = l_oDoc.MultiVolumePath
                            };

                            l_oObservableCollection.Add(l_oWCFDoc);
                        }

                        //Move the physical document which has been indexed
                        WCFService.RioWcfServices.WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                        L_oWCFServiceClient.MoveImportDocumentCompleted += MoveImportDocumentCompleted;
                        L_oWCFServiceClient.MoveImportDocumentAsync(l_oObservableCollection, GlobalWebContext.CurrentUser.UserId, ServiceManager.GetLicenseKey(), result.UserState);
                    }
                    else
                    {
                        throw new Exception(l_oFirst.ErrorMessage);
                    }
                }
                else
                {
                    //Fix chrono number is needed
                    if (!string.IsNullOrEmpty(ChronoName))
                    {
                        GetDataContext.FixChrono(ChronoName, OnFixChronoCallback, null);
                    }

                    //Active the Panel
                    m_iActivePanel--;
                    if (m_iActivePanel <= 0)
                    {
                        OnIndexed();
                        ActivatePanel();
                        SplashScreenManager.Stop(this);
                    }

                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", String.Format(m_szLabelIndexedDocument, m_iCounterIndexedDocOk, m_iCounterErrorOnIndex), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                    L_oMessage.Show();

                    L_oMessage.Closed += (s, ev) =>
                    {
                        //If this checkbox is unchecked we clear criterias
                        if (checkBoxKeepCriteria.IsChecked == false)
                        {
                            ClearCriterias();
                        }
                    };
                }
            }
            catch (Exception ex)
            {
                //Active the Panel
                m_iActivePanel--;
                if (m_iActivePanel == 0)
                {
                    OnIndexed();
                    ActivatePanel();
                    SplashScreenManager.Stop(this);
                }
                if (m_iNumberOfDocAdd == m_iNumberOfAddedDoc)
                {
                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", "Indexation Error - " + ex.Message,
                        MessageBoxButtons.Ok, MessageBoxIcon.Error);
                    L_oMessage.Show();
                }
            }
        }

        /// <summary>
        /// The Physical document has moved
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.MoveImportDocumentCompletedEventArgs"/> instance containing the event data.</param>
        private void MoveImportDocumentCompleted(object sender, WCFService.RioWcfServices.MoveImportDocumentCompletedEventArgs e)
        {
            try
            {

                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                ObservableCollection<WCFService.RioWcfServices.Document> l_oObservableCollection = e.Result;
                ImageRio l_sUserState = e.UserState as ImageRio;

                if (e.UserState != null && e.UserState.GetType().Equals(typeof(ImageRio)))
                    l_sUserState = e.UserState as ImageRio;

                List<String> l_oDocumentIdentifierList = new List<string>();
                foreach (WCFService.RioWcfServices.Document l_oDoc in l_oObservableCollection)
                {
                    if (!String.IsNullOrEmpty(l_oDoc.ErrorMessage))
                    {
                        m_iCounterErrorOnIndex++;

                        try
                        {
                            var query = l_oBEDomainContext.RemoveDocumentQuery(l_oDoc.Identifier);
                            l_oBEDomainContext.Load(query);

                            MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szLabelIndexedDocumentFailed, MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                            L_oMessage.Show();
                        }
                        catch (Exception)
                        {
                            //Active the Panel
                            m_iActivePanel--;
                            if (m_iActivePanel == 0)
                            {
                                OnIndexed();
                                ActivatePanel();
                                SplashScreenManager.Stop(this);
                            }
                        }
                    }
                    else
                    {
                        m_iCounterIndexedDocOk++;
                        l_oDocumentIdentifierList.Add(Convert.ToString(l_oDoc.Identifier));
                        if (m_oListVignetteFromImportPage.RankedListFromViewer != null)
                            if (l_sUserState != null)
                                m_oListVignetteFromImportPage.RankedListFromViewer.Remove(l_sUserState.Name);
                    }
                }

                if (l_oDocumentIdentifierList.Count > 0 && checkBoxFullText.IsChecked.Value)
                {
                    GetDataContext.UpdateDocumentsForFullText(String.Join(",", l_oDocumentIdentifierList.ToArray()));
                }

                if ((m_iCounterErrorOnIndex + m_iCounterIndexedDocOk) == m_iNumberOfDocumentToAdd)
                {
                    AddHistoricIndexation();

                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", String.Format(m_szLabelIndexedDocument, m_iCounterIndexedDocOk, m_iCounterErrorOnIndex), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                    L_oMessage.Show();

                    L_oMessage.Closed += (s, ev) =>
                    {
                        bool bMustRefresh = true;
                        if (m_DirectoryListToImport.Count > 0)
                        {
                            bMustRefresh = false;
                            DeleteDirectoriesWcfCall(m_DirectoryListToImport);
                        }
                        if (l_sUserState != null && l_sUserState.isInsideDirectory)
                        {
                            // check if the RootDirectoryName is empty, if true delete directory then return to the root
                            WCFService.RioWcfServices.WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                            L_oWCFServiceClient.ImportDirectoryIsEmptyCompleted += ((obj, args) =>
                            {
                                if (args.Result.Value)
                                {
                                    bMustRefresh = false;
                                    m_oListVignetteFromImportPage.CurrentSelectedDirectory = string.Empty;
                                    m_oListViewer.CurrentSelectedDirectory = string.Empty;
                                    m_oViewerControlFromImportPage.CurrentSelectedDirectory = string.Empty;
                                    DeleteDirectoryWcfCall(l_sUserState.RootDirectoryName);
                                }
                            });
                            L_oWCFServiceClient.ImportDirectoryIsEmptyAsync(l_sUserState.RootDirectoryName, GlobalWebContext.CurrentUser.UserId, ServiceManager.GetLicenseKey());
                        }

                        //reload interface
                        if (bMustRefresh)
                        {
                            RefreshViewer();
                        }

                        //Fix chrono number if needed
                        if (!string.IsNullOrEmpty(ChronoName))
                        {
                            GetDataContext.FixChrono(ChronoName, OnFixChronoCallback, null);
                        }
                        else
                        {
                            //If this checkbox is unchecked we clear criterias
                            if (checkBoxKeepCriteria.IsChecked == false)
                            {
                                ClearCriterias();
                            }
                        }

                        stackIndex.RevertBorderColor();
                    };

                    //Active the Panel
                    m_iActivePanel--;
                    if (m_iActivePanel == 0)
                    {
                        OnIndexed();
                        ActivatePanel();
                        SplashScreenManager.Stop(this);

                        if (m_oListSelectedFilename != null)
                        {
                            m_oListSelectedFilename.Clear();
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                SplashScreenManager.Stop(this);
                ErrorPage errorPage = new ErrorPage(ex, "IndexPanel - MoveImportDocumentCompleted error");
                errorPage.Show();

                //Logger.Write("EXCEPTION : " + Environment.NewLine + ex.ToString(), Logger.Level.Error);
            }
        }

        /// <summary>
        /// Used to delete an import directory then refresh viewer
        /// </summary>
        private new void DeleteDirectoriesWcfCall(List<ImageRio> DirectoryList)
        {
            WCFService.RioWcfServices.WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
            L_oWCFServiceClient.DeleteImportDirectoriesCompleted += ((obj, args) =>
            {
                RefreshViewer();
            });
            ObservableCollection<string> dir = new ObservableCollection<string>();
            foreach (ImageRio img in DirectoryList)
            {
                dir.Add(img.Name);
            }
            L_oWCFServiceClient.DeleteImportDirectoriesAsync(dir, GlobalWebContext.CurrentUser.UserId, ServiceManager.GetLicenseKey());
        }

        /// <summary>
        /// Used to delete an import directory then refresh viewer
        /// </summary>
        private new void DeleteDirectoryWcfCall(string DirectoryName)
        {
            WCFService.RioWcfServices.WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
            L_oWCFServiceClient.DeleteImportDirectoriesCompleted += ((obj, args) =>
            {
                RefreshViewer();
            });
            ObservableCollection<string> dir = new ObservableCollection<string>() { DirectoryName };
            L_oWCFServiceClient.DeleteImportDirectoriesAsync(dir, GlobalWebContext.CurrentUser.UserId, ServiceManager.GetLicenseKey());
        }

        /// <summary>
        /// Used to refresh all viewer
        /// </summary>
        private new void RefreshViewer()
        {
            m_oListVignetteFromImportPage.LoadVignettes(-1, true);
            m_oListViewer.RefreshItems(true);
            m_oViewerControlFromImportPage.RefreshItems(true);
        }

        /// <summary>
        /// Adds the historic indexation.
        /// </summary>
        private void AddHistoricIndexation()
        {
            //Create list of IndexValue + IndexId + IndexLabel
            List<HistoricIndex> historicIndexList = stackIndex.GetListIndexForHistorical();

            //Seralize list
            string historicIndexListSerialized = SerializationHelper.Serialize<List<HistoricIndex>>(historicIndexList);

            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();
            var query = businessEntitiesDomainContext.AddHistoricInfoConsultQuery(
                (int)Constant.UserActions.AJOUT_DOCUMENTS_DOSSIER,
                m_oFolderType.Identifier,
                0,
                null,
                null,
                null,
                historicIndexListSerialized,
                false,
                0,
                0,
                m_iCounterIndexedDocOk,
                                       treeViewControlItems.CurrentSelectedItem != null ? treeViewControlItems.CurrentSelectedItem.Text : string.Empty);

            businessEntitiesDomainContext.Load(query);
        }

        /// <summary>
        /// Indexes the panel_ search finished.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void IndexPanel_SearchFinished(object sender, ObservableCollection<Folder> e)
        {
            SearchFinished -= IndexPanel_SearchFinished;

            if (e.Count == 0)
            {
                /*
                * No Folder
                */
                MessageBoxChildWindow msg = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxCommon.SEARCH_RESULT_IS_EMPTY), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                msg.Show();
            }
            else if (e.Count == 1)
            {
                /*
                * Just 1 so we fill index values
                */
                LoadSelectedFolderInformation(null, e.FirstOrDefault(), m_oFolderType, m_oOrganization);
            }
            else
            {
                /*
                * Several folders, so we display the popup
                */
                FolderSearchChildWindow window = new FolderSearchChildWindow(GlobalWebContext.CurrentUser, m_oOrganization, m_oFolderType, stackIndex.GetIndexValuesToSearch(), e)
                {
                    Width = ((UserControl)Application.Current.RootVisual).ActualWidth - 30,
                    Height = ((UserControl)Application.Current.RootVisual).ActualHeight - 30,
                };

                window.LoadSelectedFolderInformationFromList += LoadSelectedFolderInformation;

                window.ShowDialog();
            }
        }

        /// <summary>
        /// Loads the selected folder information.
        /// </summary>
        /// <param name="P_oFolder">The folder.</param>
        /// <param name="P_oFolderType">Type of the folder.</param>
        /// <param name="P_oOrganization">The organization.</param>
        private void LoadSelectedFolderInformation(object sender, Folder P_oFolder, FolderType P_oFolderType, Organization P_oOrganization)
        {
            if (sender != null)
            {
                FolderSearchChildWindow windowSource = sender as FolderSearchChildWindow;
                windowSource.LoadSelectedFolderInformationFromList -= LoadSelectedFolderInformation;
            }

            CurrentFolder = P_oFolder;

            if (uCOrganizationType.SelectedOrganization != P_oOrganization)
                uCOrganizationType.SelectedOrganization = P_oOrganization;

            if (uCOrganizationType.SelectedFolderType != P_oFolderType)
                uCOrganizationType.SelectedFolderType = P_oFolderType;

            InitPanelControls();
        }

        /// <summary>
        /// Inits the criteria checkbox.
        /// </summary>
        private void InitCriteriaCheckbox()
        {
            SettingsDomainContext l_sdcSettingsDomainContext = new SettingsDomainContext();
            l_sdcSettingsDomainContext.GetKeepCriteria(delegate(InvokeOperation<bool> ret)
            {
                checkBoxKeepCriteria.IsChecked = ret.Value;
            },
                null);
        }

        /// <summary>
        /// Minimizes the control toolbar.
        /// </summary>
        /// <param name="minimizeToolbar">if set to <c>true</c> [minimize toolbar].</param>
        private void MinimizeControlToolbar(bool minimizeToolbar)
        {
            if (minimizeToolbar)
                VisualStateManager.GoToState(this, "Minimized", false);
            else
                VisualStateManager.GoToState(this, "Default", false);
        }

        #endregion

        #region Specific Flow

        /// <summary>
        /// Ventil the document after the chrono has been fixed
        /// </summary>
        /// <param name="p_oResult"></param>
        private void OnFixChronoCallback(InvokeOperation<ReturnBoolean> p_oResult)
        {
            ReturnBoolean l_oReturn = p_oResult.Value;
            if (l_oReturn.IsValid)
            {
                //Remove chrono and Clear the folder indexes
                stackIndex.RemoveChrono();
                ChronoName = string.Empty;
                ChronoId = 0;
                stackIndex.ClearCriterias();
                ClearDocumentInformation();
                checkBoxFullText.IsChecked = true;
            }
        }

        /// <summary>
        /// Handles the ChronoNumberGenerated event of the StackIndex control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.CriteriaControls.StackIndexControl.ChronoNumberGeneratedEventArgs" /> instance containing the event data.</param>
        private void StackIndex_ChronoNumberGenerated(object sender, StackIndexControl.ChronoNumberGeneratedEventArgs args)
        {
            ChronoName = args.ChronoName;
            ChronoId = args.ChronoId;
        }

        #endregion

        #region Specific OCR

        /// <summary>
        /// Does the OCR process.
        /// </summary>
        private void DoOCRProcess()
        {
            if (m_oListVignetteFromImportPage.ListBoxVignette != null)
            {
                SplashScreenManager.Wait(this);
                // Checked number of selected document
                if (m_oListVignetteFromImportPage.ListBoxVignette.SelectedItems.Count == 0)
                {
                    // No document selected
                    MessageBoxChildWindow L_oMessageNoDocumentSelected = new MessageBoxChildWindow("", m_szMsgNoDocumentSelected, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                    L_oMessageNoDocumentSelected.Show();
                    SplashScreenManager.Stop(this);
                }
                else
                {
                    // Get OcrMask List by folder type selected
                    try
                    {
                        var query = GetDataContext.GetOcrMaskListQuery(m_oFolderType.Identifier);
                        GetDataContext.Load(query, OnGetOcrMaskListQueryCallback, null);
                    }
                    catch (Exception)
                    {
                        SplashScreenManager.Stop(this);
                        //Logger.Write("EXCEPTION : " + Environment.NewLine + ex, Logger.Level.Error);
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void l_oOCRConflictWindow_Closed(object sender, EventArgs e)
        {
            OcrConflictChildWindow L_oOcrConflictChildWindow = sender as OcrConflictChildWindow;

            if (L_oOcrConflictChildWindow.DialogResult == true)
            {
                // set Ocr value in index panel 
                SetIndexFromOcr(L_oOcrConflictChildWindow.NewOCRConflictIndex);
            }
            else
            {
                SplashScreenManager.Stop(this);
            }
        }

        /// <summary>
        /// Set index value 
        /// </summary>
        /// <param name="P_oOcrItemList">Ocr Result</param>
        private void SetIndexFromOcr(List<OcrItem> P_oOcrItemList)
        {
            foreach (OcrItem L_oOcrItem in P_oOcrItemList)
            {
                try
                {
                    stackIndex.SetIndexValueById(L_oOcrItem.OcrIndex.Indentifier, L_oOcrItem.OcrValueList.First());
                }
                catch (Exception)
                {
                    SplashScreenManager.Stop(this);
                }
            }
            SplashScreenManager.Stop(this);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="result"></param>
        private void OnGetOcrMaskListQueryCallback(LoadOperation<OcrMask> result)
        {
            List<OcrMask> L_oOcrMaskList = new List<OcrMask>(result.Entities);
            List<RIOWCFSERVICE.ImageRio> L_oSelectedDocuments = m_oListVignetteFromImportPage.GetSelectedImage<Rio.Framework.WCFService.RioWcfServices.ImageRio>();
            List<long> L_oOcrMaskIdentifierList = new List<long>();
            List<string> L_oOcrMaskThumbnailNameList = new List<string>();

            // Number of OcrMask
            switch (L_oOcrMaskList.Count)
            {
                case 0:
                    // No ocrmask found
                    MessageBoxChildWindow L_oMessageNoOcrMaskFound = new MessageBoxChildWindow("", m_szMsgNoOcrMaskFound, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                    L_oMessageNoOcrMaskFound.Show();
                    L_oMessageNoOcrMaskFound.Focus();
                    SplashScreenManager.Stop(this);
                    break;
                case 1:
                    // Only one Ocrmask found : process ocr for all document with this mask
                    foreach (RIOWCFSERVICE.ImageRio L_oImgRio in L_oSelectedDocuments)
                    {
                        L_oOcrMaskIdentifierList.Add(L_oOcrMaskList.First().Identifier);
                        L_oOcrMaskThumbnailNameList.Add(Utils.RemoveExtension(L_oImgRio.Name));
                    }
                    RunOcr(L_oOcrMaskThumbnailNameList, L_oOcrMaskIdentifierList);
                    break;
                default:
                    // More than one : User must determine what ocrmasks to use
                    OCRMaskChildWindow L_oOcrMaskChildWindow = new OCRMaskChildWindow(L_oSelectedDocuments, L_oOcrMaskList);
                    L_oOcrMaskChildWindow.Show();
                    L_oOcrMaskChildWindow.Closed += (s, ev) =>
                    {
                        if (L_oOcrMaskChildWindow.DialogResult == true)
                        {
                            // process ocr from choice
                            if (L_oOcrMaskChildWindow.OcrMaskList.Count > 0)
                            {
                                RunOcr(L_oOcrMaskChildWindow.OcrThumbNailNameList, L_oOcrMaskChildWindow.OcrMaskList);
                            }
                            else
                            {
                                SplashScreenManager.Stop(this);
                            }
                        }
                        else
                        {
                            SplashScreenManager.Stop(this);
                        }
                    };
                    break;
            }
        }

        /// <summary>
        /// process ocr
        /// </summary>
        /// <param name="P_oOcrThumbNailNameList">List of selected document</param>
        /// <param name="P_oOcrMaskList"> list of ocrmask id to use</param>
        private void RunOcr(List<string> P_oOcrThumbNailNameList, List<long> P_oOcrMaskList)
        {
            try
            {
                var query = GetDataContext.ProcessOcrQuery(P_oOcrThumbNailNameList, P_oOcrMaskList);
                GetDataContext.Load(query, OnProcessOcrQueryQueryCallback, null);
            }
            catch (Exception)
            {
                SplashScreenManager.Stop(this);
                //Logger.Write("EXCEPTION : " + Environment.NewLine + ex, Logger.Level.Error);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="result"></param>
        private void OnProcessOcrQueryQueryCallback(LoadOperation<OcrItem> result)
        {
            List<OcrItem> L_oOcrMaskList = new List<OcrItem>(result.Entities);
            bool L_bConflictWindowLaunch = false;

            // If Ocritem value has more than one result, launch conflict window
            foreach (OcrItem L_oOcrItem in L_oOcrMaskList)
            {
                if (L_oOcrItem.OcrValueList.Count() > 1)
                {
                    L_bConflictWindowLaunch = true;
                    OcrConflictChildWindow l_oOCRConflictWindow = new OcrConflictChildWindow(L_oOcrMaskList);
                    l_oOCRConflictWindow.Show();
                    l_oOCRConflictWindow.Closed += l_oOCRConflictWindow_Closed;
                    break;
                }
            }

            if (!L_bConflictWindowLaunch)
            {
                SetIndexFromOcr(L_oOcrMaskList);
            }
        }

        #endregion

        #region Barcode Process

        /// <summary>
        /// Does the barcode process.
        /// </summary>
        private void DoBarcodeProcess()
        {
            try
            {

                Dictionary<long, string> l_oCriteriaFilter = stackIndex.GetIndexIdValues();
                List<ImageRio> images = m_oListVignetteFromImportPage.GetAllItems();
                if (images.Count == 0)
                {
                    //no images founds
                    MessageBoxChildWindow L_oEmptyDirectoryMsg = new MessageBoxChildWindow("", Resx.GetLabel(ResxIndexPanel.BARCODE_NOIMAGE_TOPROCESS), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                    L_oEmptyDirectoryMsg.Show();
                    return;
                }

                long? organizationId = null;
                long? folderTypeId = null;
                if (m_oOrganization != null)
                {
                    organizationId = m_oOrganization.Identifier;
                }
                if (m_oFolderType != null)
                {
                    folderTypeId = m_oFolderType.Identifier;
                }
                else
                {
                    organizationId = null;
                }

               
                if (organizationId == null && folderTypeId == null)
                {
                    //In this case check if the user have access to a folder sep 
                    BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                    var query = businessEntitiesDomainContext.GetFolderSeparatorBarcodesQuery();
                    businessEntitiesDomainContext.Load(
                        query,
                        result =>
                            {
                                if (!result.HasError && result.Entities != null
                                    && result.Entities.Any())
                                {
                                    bool hasFolderSepAccess = GlobalWebContext.GetUserCanProcessBarcode(new List<Barcode>(result.Entities));

                                    if (!hasFolderSepAccess)
                                    {
                                        MessageBoxChildWindow L_oEmptyDirectoryMsg = new MessageBoxChildWindow("", Resx.GetLabel(ResxIndexPanel.BARCODE_CHOOSE_ORG), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                                        L_oEmptyDirectoryMsg.Show();
                                        return;
                                    }

                                    //process barcode
                                    SplashScreenManager.Wait(this);
                                    _barcodeManager.PreProcessBarcode(images.Select(p => Utils.RemoveExtension(p.Name)).ToList(),
                                                                           organizationId,
                                                                           folderTypeId,
                                                                           l_oCriteriaFilter,
                                                                           checkBoxFullText.IsChecked.Value,
                                                                           textboxNote.Text,
                                                                           textboxAuthor.Text);
                                }
                            },
                        null);


                }
                else
                {
                    //BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
                    //var query = businessEntitiesDomainContext.GetFolderSeparatorBarcodesQuery();
                    //businessEntitiesDomainContext.Load(
                    //    query,
                    //    result =>
                    //    {
                    //        if (!result.HasError && result.Entities != null
                    //            && result.Entities.Any())
                    //        {
                    //            bool hasFolderSepAccess = GlobalWebContext.GetUserCanProcessBarcode(new List<Barcode>(result.Entities));
                    //            if (!hasFolderSepAccess)
                    //            {
                    //                if (!stackIndex.IsMandatoryIndexSatisfied())
                    //                {
                    //                    MessageBoxChildWindow L_oEmptyDirectoryMsg = new MessageBoxChildWindow("", Resx.GetLabel(ResxIndexPanel.BARCODE_TYPE_INDEX), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                    //                    L_oEmptyDirectoryMsg.Show();
                    //                    return;
                    //                }
                    //            }

                                //process barcode
                                SplashScreenManager.Wait(this);
                                _barcodeManager.PreProcessBarcode(images.Select(p => Utils.RemoveExtension(p.Name)).ToList(),
                                                                       organizationId,
                                                                       folderTypeId,
                                                                       l_oCriteriaFilter,
                                                                       checkBoxFullText.IsChecked.Value,
                                                                       textboxNote.Text,
                                                                       textboxAuthor.Text);
                        //    }
                        //},
                        //null);
                }

            }
            catch (Exception ex)
            {
                MessageBoxChildWindow L_oEmptyDirectoryMsg = new MessageBoxChildWindow("", ex.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oEmptyDirectoryMsg.Show();
            }
        }

        /// <summary>
        /// Handles the BarcodeProcessed event of the barcodeManager control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Events.BarcodeEventArgs" /> instance containing the event data.</param>
        private void barcodeManager_BarcodeProcessed(object sender, Events.BarcodeEventArgs args)
        {
            SplashScreenManager.Stop(this);

            //No barcode found
            if(_barcodeManager.FoundBarcode.Count == 0)
            {
                MessageBoxChildWindow L_oEmptyDirectoryMsg = new MessageBoxChildWindow("", Resx.GetLabel(ResxIndexPanel.BARCODE_NOBRACODE_FOUND), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                L_oEmptyDirectoryMsg.Show();
                return;
            }

            //Apply rules
            List<BarcodeManager.FolderDataContext> folders = _barcodeManager.GetFolderBlocksToIndexes();
            if (folders != null && folders.Count > 0)
            {
                //Check if the first folder is separator with correspondence
                bool firstImageIsFolderSeparatorWithCorrespondence = false;
                var firstFolder = folders.FirstOrDefault();
                if (firstFolder != null
                    && firstFolder.Separator != null
                    && firstFolder.Separator.TypeOfBarcode == BarcodeSeparatorType.FolderSeparator
                    && firstFolder.Separator.CorrespondenceFolder)
                {
                    //the first folder is a folder sep
                    firstImageIsFolderSeparatorWithCorrespondence = true;
                }
                bool hasFolderSeparatorWithCorrespondence = folders.Any(f => f.Separator != null && f.Separator.TypeOfBarcode == BarcodeSeparatorType.FolderSeparator && f.Separator.CorrespondenceFolder);

                //If no organization and folder type selected
                if (_barcodeManager.DefaultOrganizationId == null && _barcodeManager.DefaultFolderTypeId == null)
                {
                    //If the first image is a valid folder separator with correspondence
                    if (firstImageIsFolderSeparatorWithCorrespondence)
                    {
                        folders = _barcodeManager.CleanFolderWithoutCorrespondence(folders);
                        ShowCBDialogResult(folders);
                        return;
                    }

                    //There's one folder separator with correspondence but not in first
                    if (hasFolderSeparatorWithCorrespondence)
                    {
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", Resx.GetLabel(ResxIndexPanel.Barcode_Unvalid_FolderBlock), MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                        L_oMessage.Show();
                        L_oMessage.Closed += (s, ev) =>
                        {
                            if (L_oMessage.Result == MessageBoxResult.Yes)
                            {
                                folders = _barcodeManager.CleanFolderWithoutCorrespondence(folders);
                                ShowCBDialogResult(folders);
                            }
                        };
                    }

                    //There's no folder separator
                    if(!hasFolderSeparatorWithCorrespondence)
                    {
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", Resx.GetLabel(ResxIndexPanel.BARCODE_NOBARCODESEP_FOUND), MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                        L_oMessage.Show();
                    }
                }
                else
                {
                    //If the first image is a valid folder separator with correspondence
                    if (firstImageIsFolderSeparatorWithCorrespondence)
                    {
                        folders = _barcodeManager.CleanFolderWithoutCorrespondence(folders);
                        ShowCBDialogResult(folders);
                        return;
                    }

                    //There's one folder separator with correspondence but not in first
                    if (hasFolderSeparatorWithCorrespondence)
                    {
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", Resx.GetLabel(ResxIndexPanel.Barcode_Unvalid_FolderBlock), MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                        L_oMessage.Show();
                        L_oMessage.Closed += (s, ev) =>
                        {
                            if (L_oMessage.Result == MessageBoxResult.Yes)
                            {
                                folders = _barcodeManager.CleanFolderWithoutCorrespondence(folders);
                                ShowCBDialogResult(folders);
                            }
                        };
                        return;
                    }


                    // No barcode folder separator, document separator only
                    //If all mandatory criteria are inputed, we can follow the indexation
                    SplashScreenManager.Wait(this);
                    Dictionary<long, string> l_oUnicityIndex;
                    if (!stackIndex.IsMandatoryIndexSatisfied())
                    {
                        SplashScreenManager.Stop(this);
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("", m_szLabelMandatoryField, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                        L_oMessage.Show();
                    }
                    else
                    {
                        Dictionary<long, string> l_oCriteriaFilter = stackIndex.GetIndexIdValues();
                        l_oUnicityIndex = stackIndex.GetUniqueIndexValues();

                        //** check if folder exist with specified index
                        GetDataContext.IsFolderExist(m_oOrganization.Identifier, m_oFolderType.Identifier, l_oCriteriaFilter, false, delegate(InvokeOperation<ReturnLong> retr)
                        {
                            SplashScreenManager.Stop(this);
                            if (retr != null && retr.Value != null && retr.Value.Value != 0)
                            {
                                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(string.Empty, m_szMsgFolderExists, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                                L_oMessage.Show();
                                L_oMessage.Closed += (s, ev) =>
                                {
                                    if (L_oMessage.Result == MessageBoxResult.Yes)
                                    {
                                        ShowCBDialogResult(folders);
                                    }
                                };
                            }
                            else
                            {
                                //** if no folder found check unicity of the index
                                GetDataContext.CheckUnicityOfIndexValue(m_oFolderType.Identifier, l_oUnicityIndex, 0, delegate(InvokeOperation<IEnumerable<long>> CheckUnicityReturn)
                                {
                                    SplashScreenManager.Stop(this);
                                    if (CheckUnicityReturn.Value != null && !CheckUnicityReturn.Value.Any())
                                    {
                                        ShowCBDialogResult(folders);
                                    }
                                    else
                                    {
                                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(string.Empty, m_szMsgNoUnicity, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                                        L_oMessage.Show();
                                    }
                                }, null); //CheckUnicityOfIndexValue
                            }
                        }, null);//IsFolderExist
                    }

                }
            }
        }

        /// <summary>
        /// Shows the CB dialog result.
        /// </summary>
        /// <param name="folders">The folders.</param>
        private void ShowCBDialogResult(List<Rio.Framework.Pages.Manager.BarcodeManager.FolderDataContext> folders)
        {
            SplashScreenManager.Stop(this);
            BarcodeResultChildWindow bcResultChild = new BarcodeResultChildWindow
            {
                Folders = new ObservableCollection<BarcodeManager.FolderDataContext>(folders)
            };

            bcResultChild.Closed += delegate
            {
                if (bcResultChild.DialogResult == true)
                {
                    //Run indexing with all images 
                    _barcodeManager.ProcessFolders(folders);
                }
            };

            bcResultChild.ShowDialog();
        }

        /// <summary>
        /// Handles the BeforeIndexing event of the barcodeManager control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void barcodeManager_BeforeIndexing(object sender, EventArgs e)
        {
            SplashScreenManager.Wait(this);
        }

        /// <summary>
        /// Handles the IndexingFinished event of the _barcodeManager control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Events.BarcodeEventArgs" /> instance containing the event data.</param>
        private void barcodeManager_IndexingFinished(object sender, Events.BarcodeEventArgs args)
        {
            SplashScreenManager.Stop(this);

            MessageBoxChildWindow message = new MessageBoxChildWindow("", String.Format(m_szLabelIndexedDocument, args.ProcessedFilesCount, args.ErrorFilesCount), MessageBoxButtons.Ok, MessageBoxIcon.Information);
            message.Show();
            message.Closed += (s, ev) =>
            {
                RefreshViewer();
                OnIndexed();
                ActivatePanel();
            };
        }

        /// <summary>
        /// Handles the IndexingError event of the barcodeManager control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void barcodeManager_IndexingError(object sender, Events.BarcodeEventArgs e)
        {
            SplashScreenManager.Stop(this);

            MessageBoxChildWindow message = new MessageBoxChildWindow("", e.Error, MessageBoxButtons.Ok, MessageBoxIcon.Error);
            message.Show();
            message.Closed += (s, ev) =>
            {
                RefreshViewer();
                ActivatePanel();
            };
        }

        /// <summary>
        /// Handles the NeedIndexCriteria event of the barcodeManager control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Events.BarcodeIndexingEventArgs" /> instance containing the event data.</param>
        private void barcodeManager_NeedIndexCriteria(object sender, Events.BarcodeIndexingEventArgs args)
        {
            args.Cancel = true;
            MessageBoxChildWindow message = new MessageBoxChildWindow("", "Le séparateur de dossier ne contient pas d'index!", MessageBoxButtons.Ok, MessageBoxIcon.Warning);
            message.Show();
        }

        /// <summary>
        /// Handles the IndexingAborted event of the barcodeManager control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void barcodeManager_IndexingAborted(object sender, EventArgs e)
        {
            SplashScreenManager.Stop(this);

            MessageBoxChildWindow message = new MessageBoxChildWindow("", "Indexation annulée", MessageBoxButtons.Ok, MessageBoxIcon.Information);
            message.Show();
        }
        #endregion

        private void checkBoxProcessCAB_Click(object sender, RoutedEventArgs e)
        {
            if (checkBoxProcessCAB.IsChecked != null && checkBoxProcessCAB.IsChecked.Value)
            {
                checkBoxProcessLAD.IsChecked = false;
                buttonToIndex.IsEnabled = true;
            }
            else
            {
                if (m_oFolderType == null && m_oOrganization == null)
                {
                    buttonToIndex.IsEnabled = false;
                }
            }
        }

        private void checkBoxProcessLAD_Click(object sender, RoutedEventArgs e)
        {
            if (checkBoxProcessLAD.IsChecked != null && checkBoxProcessLAD.IsChecked.Value)
            {
                checkBoxProcessCAB.IsChecked = false;
            }
        }
    }


    public class ItemNameToOutlookBarItem : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value == null
                       ? Resx.GetLabel(ResxIndexPanel.ITEMS)
                       : String.Format("{0} : {1}",
                                       Resx.GetLabel(ResxIndexPanel.ITEMS),
                                       ((DataItemTreeView)value).Text);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
